//
//  personalViewController.m
//  dangdang
//
//  Created by air on 15/12/8.
//  Copyright © 2015年 luweijie. All rights reserved.
//

#import "PersonalViewController.h"
#import "Profile.h"
#import "ProfileDataSource.h"
#import "TransactionDetailTableViewController.h"
#import "ExpenditureDetailTableViewController.h"
#import "RechargeRecordTableViewController.h"
#import "RefundRecordTableViewController.h"
#import "HomepageViewController.h"
#import "OrderViewController.h"
#import "PersonalProfileViewController.h"
#import "InProgressViewController.h"
#import "EvaluateViewController.h"
#import "CompleteViewController.h"
#import "RefundViewController.h"
#import "CancelViewController.h"
#import "PersonalFirstTableViewCell.h"
#import "PersonalSecondTableViewCell.h"
#import "PersonalThirdTableViewCell.h"
#import "PersonalForthTableViewCell.h"
#import "PersonalFifthTableViewCell.h"
#import "PersonalSixthTableViewCell.h"
#import "PersonalSeventhTableViewCell.h"
#import "SetViewController.h"
#import "MessageViewController.h"
#import "BillDetailsViewController.h"
#import "MyBillViewController.h"
#import "ApplyViewController.h"
#import "UIImageView+WebCache.h"
#import "LoginViewController.h"

@interface PersonalViewController ()

@property (nonatomic, copy) NSString * urlString;
@property (nonatomic, copy) NSString * utype;
@property (nonatomic, strong) NSData * data;

@end

@implementation PersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self connection];
    
    [self updateUI];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}

- (void)addBottomView{
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.center.x - 60, self.view.bounds.size.height - 120, 120, 40)];
    __block int timeout = 2; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [label removeFromSuperview];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                label.backgroundColor = [UIColor blackColor];
                label.text = @"提交完成";
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.font = [UIFont boldSystemFontOfSize:16.0f];
                label.layer.cornerRadius = 10;
                label.layer.masksToBounds = YES;
                [self.view addSubview:label];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)connection{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"0wtcDflIXFLHx4VJ3G32cuFGg" forKey:@"appSecret"];
    
    [self postRequestWithMethodName:@"auth/accesstoken" andParams:params andSender:nil];
}

- (void)updateUI{
    NSLog(@"12313123");
    if ([userObject.personString isEqualToString:@"1"]) {
        _headImageView = userObject.personImageView;
        _nameLabel.text = userObject.name;
        _phoneLabel.text = userObject.phone;
        _utype = userObject.uType;
    }
    
    if ([userObject.type isEqualToString:@"1"]) {
        _orderImageView.image = [UIImage imageNamed:@"hk_grab.png"];
    }
    
    if ([_sucessIdentify isEqualToString:@"identify"]) {
        [self addBottomView];
    }
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushPersonProfile)];
    tap.numberOfTapsRequired = 1;
    [_topView addGestureRecognizer:tap];
    
    _headImageView.layer.cornerRadius = _headImageView.frame.size.width / 2;
    _headImageView.layer.borderWidth = 1;
    _headImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
    _headImageView.layer.masksToBounds = YES;
    
    _personalTableView.rowHeight = UITableViewAutomaticDimension;
    _personalTableView.estimatedRowHeight = 44.0;
    
    _bottomView.layer.borderWidth = 1;
    _bottomView.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    _orderBackView.layer.borderWidth = 1;
    _orderBackView.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    _orderBackView.layer.cornerRadius = _orderBackView.frame.size.width / 2;
    _loginButton.layer.borderWidth = 1;
    _loginButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    _loginButton.layer.cornerRadius = 6;
    
    UITapGestureRecognizer * personalTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    personalTapGestureRecognizer.numberOfTapsRequired = 1;
    [_orderImageView addGestureRecognizer:personalTapGestureRecognizer];
    _orderImageView.userInteractionEnabled = YES;
    
    if (userObject.userID) {
        _loginButton.hidden = YES;
    }
}

- (void)pushPersonProfile{
    NSString * uid = userObject.userID;
    if (uid) {
        PersonalProfileViewController * personboardVC = [[UIStoryboard storyboardWithName:@"PersonalProfileViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalProfileViewController"];
        
        [self.navigationController pushViewController:personboardVC animated:YES];
    }
}

- (IBAction)login:(UIButton *)sender {
    LoginViewController * loginboardVC = [[UIStoryboard storyboardWithName:@"LoginViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [self.navigationController pushViewController:loginboardVC animated:YES];
}

- (IBAction)pushController:(UIButton *)sender {
    HomepageViewController * homeboardVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"HomepageViewController"];
    [self.navigationController pushViewController:homeboardVC animated:NO];
}

- (void)tapAction:(UITapGestureRecognizer *)tapGestureRecognizer{
    if ([userObject.type isEqualToString:@"1"]) {
        OrderViewController * orderboardVC = [[UIStoryboard storyboardWithName:@"OrderViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderViewController"];
        [self.navigationController pushViewController:orderboardVC animated:NO];
    }else if ([userObject.type isEqualToString:@"0"]){
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请申请成为速送员" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        }];
        
        [alertVC addAction:action];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else if (!userObject.userID){
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            LoginViewController * personalboardVC = [[UIStoryboard storyboardWithName:@"LoginViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
            [self.navigationController pushViewController:personalboardVC animated:NO];
        }];
        
        [alertVC addAction:action];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (IBAction)setOrClockButton:(UIButton *)sender {
    if (sender.tag == 0) {
        SetViewController * setboardVC = [[UIStoryboard storyboardWithName:@"SetViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"SetViewController"];
        [self.navigationController pushViewController:setboardVC animated:YES];
    }else{
        MessageViewController * messageboardVC = [[UIStoryboard storyboardWithName:@"MessageViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"MessageViewController"];
        
        messageboardVC.message = @"此验证码只用于订单完成，请勿在未完成订单前清除，653450,此验证码只用于订单完成，请勿在未完成订单前清除，653450";
        messageboardVC.message2 = @"2016-03-21 18:30:30";
        
        [self.navigationController pushViewController:messageboardVC animated:NO];
    }
}

- (IBAction)onLine:(UISwitch *)sender {
    BOOL isOnLine = [sender isOn];
    if (isOnLine) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:@"1" forKey:@"status"];
        
        [self postRequestWithMethodName:@"courier/switch_status" andParams:params andSender:nil];
    }else{
        userObject.isWork = NO;
    }
}

#pragma mark UITableViewDataSource && Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_utype isEqualToString:@"1"]) {
        if (section == 0) {
            return 2;
        }else if (section == 1){
            return 3;
        }else{
            return 2;
        }
    }else{
        if (section == 0) {
            return 1;
        }else if (section == 1){
            return 3;
        }else{
            return 2;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        PersonalFirstTableViewCell * firstCell = [tableView dequeueReusableCellWithIdentifier:@"personalFirstTableViewCell"];
        
        if (![_utype isEqualToString:@"1"]) {
            for (UIImageView * imageView in firstCell.starArray) {
                imageView.hidden = YES;
            }
        }else if ([_utype isEqualToString:@"1"]){
            for (UIImageView * imageView in firstCell.starArray) {
                imageView.hidden = YES;
            }
            firstCell.titleLabel.text = @"速送员";
        }
        
        cell = firstCell;
    }else if (indexPath.section == 0 && indexPath.row == 1){
        PersonalSecondTableViewCell * secondCell = [tableView dequeueReusableCellWithIdentifier:@"personalSecondTableViewCell"];
        if (userObject.isWork == YES) {
            [secondCell.workSwitch setOn:YES];
        }
        
        cell = secondCell;
    }else if (indexPath.section == 1 && indexPath.row == 0){
        PersonalThirdTableViewCell * thirdCell = [tableView dequeueReusableCellWithIdentifier:@"personalThirdTableViewCell"];
        thirdCell.countLabel.layer.cornerRadius = thirdCell.countLabel.frame.size.width / 2;
        thirdCell.countLabel.layer.masksToBounds = YES;
//        thirdCell.countLabel.text = @"1";
        thirdCell.countLabel.hidden = YES;
        thirdCell.countLabel.font = [UIFont systemFontOfSize:12.0];
        thirdCell.countLabel.textAlignment = NSTextAlignmentCenter;
        
        cell = thirdCell;
    }else if (indexPath.section == 1 && indexPath.row == 1){
        PersonalForthTableViewCell * forthCell = [tableView dequeueReusableCellWithIdentifier:@"personalForthTableViewCell"];
        
        cell = forthCell;
    }else if (indexPath.section == 1 && indexPath.row == 2){
        PersonalFifthTableViewCell * fifthCell = [tableView dequeueReusableCellWithIdentifier:@"personalFifthTableViewCell"];
        
        cell = fifthCell;
    }else if (indexPath.section == 2 && indexPath.row == 0){
        PersonalSixthTableViewCell * sixthCell = [tableView dequeueReusableCellWithIdentifier:@"personalSixthTableViewCell"];
        
        cell = sixthCell;
    }else if (indexPath.section == 2 && indexPath.row == 1){
        PersonalSeventhTableViewCell * seventhCell = [tableView dequeueReusableCellWithIdentifier:@"personalSeventhTableViewCell"];
        
        cell = seventhCell;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    Profile * profile = [[[[ProfileDataSource alloc] init].profileList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
//    cell.imageView.image = [UIImage imageNamed:profile.pictureName];
//   cell.textLabel.text = profile.functionName;
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * uid = userObject.userID;
    if (uid) {
        if (!(indexPath.section == 0 && indexPath.row == 1)) {
            Profile * profile = [[[[ProfileDataSource alloc] init].profileList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
            if (profile.destinationName != nil && ![profile.destinationName isEqualToString:@""]) {
                if ([profile.destinationName isEqualToString:@"TransactionDetailTableViewController"]) {
                    BillDetailsViewController *pageController = [[BillDetailsViewController alloc] init];
                    NSArray *viewControllerClasses = @[[TransactionDetailTableViewController class], [ExpenditureDetailTableViewController class], [RechargeRecordTableViewController class], [RefundRecordTableViewController class]];
                    NSArray *titles = @[@"收入明细", @"支出明细", @"充值记录", @"退款记录"];
                    pageController.viewControllerClasses = viewControllerClasses;
                    pageController.titles = titles;
                    pageController.menuItemWidth = self.view.frame.size.width / 4;
                    pageController.menuViewStyle = WMMenuViewStyleLine;
                    pageController.titleSizeSelected = 15.0;
                    pageController.titleName = @"交易明细";
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:pageController];
                        [self presentViewController:navi animated:YES completion:nil];
                    });
                }else if ([profile.destinationName isEqualToString:@"InProgressViewController"]){
                    MyBillViewController *pageController = [[MyBillViewController alloc] init];
                    NSArray *viewControllerClasses = @[[InProgressViewController class], [EvaluateViewController class], [CompleteViewController class], [RefundViewController class], [CancelViewController class]];
                    NSArray *titles = @[@"进行中", @"待评价", @"已完成", @"已退款", @"已取消"];
                    pageController.viewControllerClasses = viewControllerClasses;
                    pageController.titles = titles;
                    pageController.menuItemWidth = self.view.frame.size.width / 5;
                    pageController.menuViewStyle = WMMenuViewStyleLine;
                    pageController.titleSizeSelected = 15.0;
                    pageController.titleName = @"我的订单";
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:pageController];
                        [self presentViewController:navi animated:YES completion:nil];
                    });
                }
                else if ([profile.destinationName isEqualToString:@"ApplyViewController"] && [_utype isEqualToString:@"0"]){
                    NSString * token = userObject.accessToken;
                    NSString * userIDString = userObject.userID;
                    
                    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                    [params setObject:token forKey:@"token"];
                    [params setObject:userIDString forKey:@"uid"];
                    
                    [self postRequestWithMethodName:@"courier/check_request_status" andParams:params andSender:nil];
                }
                else if (indexPath.section != 0){
                    [self.navigationController pushViewController:[[UIStoryboard storyboardWithName:profile.destinationName bundle:nil] instantiateViewControllerWithIdentifier:profile.destinationName] animated:YES];
                }
            }
        }
    }else{
        LoginViewController * loginboardVC = [[UIStoryboard storyboardWithName:@"LoginViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self.navigationController pushViewController:loginboardVC animated:YES];
    }
}

- (void)addImageView{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        NSURL *url = [NSURL URLWithString:
                      _urlString];
        NSURLSessionDownloadTask *downloadPhotoTask =[[NSURLSession sharedSession]
                                                      downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                                                          
                                                          NSLog(@"error = %@", error);
                                                          [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                                                          
                                                          dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                                              // 处理耗时操作的代码块...
                                                              UIImage *downloadedImage = [UIImage imageWithData:                                                                                          [NSData dataWithContentsOfURL:location]];
                                                              //通知主线程刷新
                                                              dispatch_async(dispatch_get_main_queue(), ^{  
                                                                  //回调或者说是通知主线程刷新，
                                                                 _headImageView.image = downloadedImage;
                                                              });
                                                        });
                                                      }];
        [downloadPhotoTask resume];
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        //        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"auth/accesstoken"]]){
            userObject.accessToken = [[result objectForKey:@"retmsg"] objectForKey:@"access_token"];
            
            NSString * token = userObject.accessToken;
            NSString * userIDString = userObject.userID;
            
            if (userIDString) {
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                [params setObject:token forKey:@"token"];
                [params setObject:userIDString forKey:@"uid"];
                
                [self postRequestWithMethodName:@"user/get_info" andParams:params andSender:nil];
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"user/get_info"]]){
            if (![userObject.personString isEqualToString:@"1"]) {
                _urlString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uhead"]];
                userObject.uType = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"utype"]];
                _utype = userObject.uType;
                
                NSURL* imagePath = [NSURL URLWithString:_urlString];
                [_headImageView sd_setImageWithURL:imagePath];
                userObject.personImageView = _headImageView;
                
                _nameLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uname"]];
                _phoneLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uphone"]];
                userObject.name = _nameLabel.text;
                userObject.phone = _phoneLabel.text;
                
                userObject.personString = @"1";
                [_personalTableView reloadData];
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"courier/check_request_status"]]){
            NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
            if ([code isEqualToString:@"1"]) {
                ApplyViewController * applyboardVC = [[UIStoryboard storyboardWithName:@"ApplyViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ApplyViewController"];
                
                [self.navigationController pushViewController:applyboardVC animated:YES];
            }else if ([code isEqualToString:@"2"]){
                [self alertViewShowWithAlertString:[NSString stringWithFormat:@"%@", [result objectForKey:@"retmsg"]]];
            }else{
                
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"courier/switch_status"]]){
            userObject.isWork = YES;
        }
    }
}

@end
